import React, {useRef} from 'react';
import {
  Animated,
  Text,
  View,
  StyleSheet,
  Button,
  SafeAreaView,
} from 'react-native';

const App = () => {
    //创建一个ref对象，用来存储动画值，初始值为0
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const moveAnim = useRef(new Animated.Value(0)).current;
  const fadeIn = () => {
    //使用timing动画，从0开始，到1结束，持续5000ms
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 5000,
      useNativeDriver: true, //使用原生动画驱动
    }).start(()=>{
        scanMove();
    });
  };

  const fadeOut = () => {
    //使用timing动画，从1开始，到0结束，持续3000ms
    Animated.timing(fadeAnim, {
      toValue: 0,
      duration: 3000,
      useNativeDriver: true, //使用原生动画驱动
    }).start();
  };

  const scanEnd = () => {
    Animated.timing(moveAnim, {
        toValue: 0,
        duration: 2000,
        useNativeDriver: true, //使用原生动画驱动
    }).start(()=>{
        scanMove();
    });
  }

  const scanMove = () => {
    Animated.timing(moveAnim, {
        toValue: 198,
        duration: 2000,
        useNativeDriver: true, //使用原生动画驱动
    }).start(()=>{
        scanEnd();
    });
  }
  

  return (
    <SafeAreaView style={styles.container}>
        <Animated.View style={{opacity: fadeAnim,}}>
            <View style={[styles.scanContainer]}>
                <Animated.View style={[styles.border, {
                    transform: [{
                        translateY: moveAnim
                    }]
                }]}>
                </Animated.View>
            </View>
        </Animated.View>
      <View style={styles.buttonRow}>
        <Button title="扫一扫" onPress={fadeIn} />
        <Button title="隐藏" onPress={fadeOut} />
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  fadingContainer: {
    padding: 20,
    backgroundColor: 'powderblue',
  },
  fadingText: {
    fontSize: 28,
  },
  buttonRow: {
    flexBasis: 100,
    justifyContent: 'space-evenly',
    marginVertical: 16,
  },
  scanContainer:{
    height: 200,
    width: 200,
    borderWidth: 1,
    borderColor: 'green',
  },
  border:{
    borderWidth: 1,
    borderColor: 'red',
  }
});

export default App;